<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * User
 * 
 * Manages user related information.
 * Operates the following tables:
 * - user
 * - contactdata
 * 
 * @package     Main
 * @author      Lukas Fritsch <jejanim@gmail.com>
 * @version     0.1 (06.08.2013)
 */    

class Usermodel extends CI_Model{
    private $tbl_user        = 'user';
    private $tbl_contactdata = 'contactdata';
    private $tbl_rating      = 'rating';
    
    
    public function __construct(){
        parent::__construct();
    }  
    
    /**
     * GET DETAILS
     * Fetches the user record of the current user
     * 
     * @return  obj / bool - either returns FALSE or an object
     */
    public function get_details($id = FALSE){
        if(!$id)                                                               
            return FALSE;
        
        $sql = 'SELECT u.id, 
                       u.username, 
                       u.avatar,
                       c.country,
                       count(d.id) as drinks
                FROM user as u
                INNER JOIN contactdata as c
                    ON u.contactdata_id = c.id
                INNER JOIN drink as d
                    ON u.id = d.user_id
                WHERE u.id=?';
        $query = $this->db->query($sql, $id);
        
        if($query->num_rows == 0)                                               
            return FALSE;
        
        return $query->row();
    }
    
    /**
     * GET RATING
     * Tries to find a rating record a user sent for a certain drink.
     * If no record exists, FALSE will be returned.
     * 
     * @param type $user_id
     * @param type $drink_id
     */
    public function get_rating($user_id = FALSE, $drink_id = FALSE){
        if(!$user_id || !$drink_id)
            return FALSE;
        
        $sql = 'SELECT *
                FROM ?
                WHERE drink_id = ? AND user_id = ?';
        
        $query = $this->db->query($sql, arrray(
                                               $this->tbl_rating, 
                                               $drink_id, 
                                               $user_id
                                              ));
        
        if($query->num_rows == 0)
            return FALSE;
        
        return $query->row();
    }
}